package com.egao.common.module.cms.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.core.exception.ParameterException;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.module.cms.entity.Article;
import com.egao.common.module.cms.entity.Link;
import com.egao.common.module.cms.mapper.LinkMapper;
import com.egao.common.module.cms.service.LinkService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 友情链接实现类
 * @author pyx
 */
@Service
public class LinkServiceImpl extends ServiceImpl<LinkMapper, Link> implements LinkService {

    @Override
    public List<Link> listPage(PageParam<Link> pageParam) {
        return baseMapper.listPage(pageParam);
    }

    @Override
    public JsonResult getId(Integer id) {
        if(id == null){
            throw new ParameterException("参数对象为空");
        }

        QueryWrapper<Link> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        Integer count = baseMapper.selectCount(wrapper);

        if(count != 1){
            throw new ParameterException("链接不存在");
        }

        Link link = baseMapper.selectById(id);
        return JsonResult.ok().setData(link);
    }

    @Override
    public JsonResult insertLink(Link link) {
        if(link == null){
            throw new ParameterException("参数对象为空");
        }

        if(StrUtil.isBlank(link.getType())){
            throw new ParameterException("链接类型不能为空");
        }
        if(StrUtil.isBlank(link.getTitle())){
            throw new ParameterException("链接标题不能为空");
        }

        baseMapper.insert(link);
        return JsonResult.ok("添加成功");
    }

    @Override
    public JsonResult updateLink(Link link) {
        if(link == null){
            throw new ParameterException("参数对象为空");
        }

        if(StrUtil.isBlank(link.getType())){
            throw new ParameterException("链接类型不能为空");
        }
        if(StrUtil.isBlank(link.getTitle())){
            throw new ParameterException("链接标题不能为空");
        }

        if(link.getSort() == null){
            link.setSort(9999);
        }

        baseMapper.updateById(link);
        return JsonResult.ok("修改成功");
    }

    @Override
    public JsonResult deleteById(Integer id) {
        if(id == null){
            throw new ParameterException("参数对象为空");
        }

        if(removeById(id)){
            return JsonResult.ok("删除成功");
        }

        return JsonResult.error("删除失败");
    }
}
